package com.itheima.interceptors;

import com.itheima.utils.AccessLimit;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.CodeSignature;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * @author ：yuan_he_song
 * @description: TODO
 * @date：2020/2/27 20:40
 */
@Component
@Aspect
public class AccessLimitAspect {

    @Pointcut("@annotation(com.itheima.utils.AccessLimit)")
    public void accessLimitCut(){
    }

    @Around("accessLimitCut()")
    public void adviceAround(ProceedingJoinPoint joinPoint) throws Throwable {
        long start = System.currentTimeMillis();
        // 获取request对象
        ServletRequestAttributes attribute = (ServletRequestAttributes)RequestContextHolder.getRequestAttributes();
        HttpServletRequest request = attribute.getRequest();

        // 获取方法上的注解
        Signature signature = joinPoint.getSignature();
        MethodSignature mg = (MethodSignature) signature;
        Method method = mg.getMethod();
        AccessLimit annotation = method.getAnnotation(AccessLimit.class);

        System.err.println("=========================请求开始=========================");
        // 请求连接
        String url = request.getRequestURL().toString();
        System.err.println("请求连接 ========> " + url);
        // 接口描述信息
        System.err.println("方法的描述 ========> " + annotation.desc());
        // 请求方法
        System.err.println("请求方法 ========> " + method.getName() + "()");
        // 请求类型
        System.err.println("请求类型 ========> " + request.getMethod() + "请求");
        // 请求IP
        System.err.println("请求IP ========> " + request.getRemoteAddr());
        // 请求入参
        Object[] args = joinPoint.getArgs();
        // 参数名
        String[] paramNames = ((CodeSignature) joinPoint.getSignature()).getParameterNames();
        for (int i = 0; i < paramNames.length; i++) {
            System.err.println("参数名:" + paramNames[i] + " --- 参数值:" + args[i]);

        }
        // 执行目标方法逻辑
        System.err.println(">>>>>>>开始执行目标方法逻辑<<<<<<<");
        joinPoint.proceed();
        System.err.println(">>>>>>>目标方法执行逻辑结束<<<<<<<");
        long end = System.currentTimeMillis();
        System.err.println("总共耗时:" + (end - start) + "ms");
        System.err.println("=========================请求结束============>");
    }
}
